<template>
  <div class="chat-container">
    <!-- Logo和标题区域 -->
    <div class="header-container">
      <img :src="logo" alt="Logo" class="logo" />
      <h1 class="chat-title">{{ title }}</h1>
    </div>

    <div class="chat-messages" ref="messagesContainer">
      <!-- 初始消息 -->
      <div class="message-wrapper ai-message" v-if="messages.length === 0">
        <div class="avatar">
          <img :src="aiAvatar" :alt="aiName" />
        </div>
        <div class="message-content">
          <div class="message-sender">{{ aiName }}</div>
          <div class="message-text">{{ initMessage }}</div>
        </div>
      </div>

      <!-- 聊天历史 -->
      <div
        v-for="(message, index) in messages"
        :key="index"
        :class="[
          'message-wrapper',
          message.role === 'user' ? 'user-message' : 'ai-message'
        ]"
      >
        <div class="avatar">
          <img
            :src="message.role === 'user' ? userAvatar : aiAvatar"
            :alt="message.role === 'user' ? userName : aiName"
          />
        </div>
        <div class="message-content">
          <div class="message-sender">
            {{ message.role === "user" ? userName : aiName }}
          </div>
          <div 
            class="message-text" 
            v-html="formatMessage(message.content)"
            :class="{'typing': isTyping && index === messages.length - 1 && message.role === 'assistant'}"
          ></div>
        </div>
      </div>

      <!-- 加载指示器 -->
      <div class="loading-indicator" v-if="isLoading && !isTyping">
        <div class="dot"></div>
        <div class="dot"></div>
        <div class="dot"></div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="chat-input-container">
      <textarea
        v-model="inputMessage"
        class="chat-input"
        placeholder="请输入消息..."
        @keydown.enter.prevent="handleEnterKey"
      ></textarea>
      <button 
        class="send-button" 
        @click="sendMessage"
        :disabled="isLoading || !inputMessage.trim()"
      >
        发送
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue';
import { useChat, type Message } from '../services/chatService';

// 从环境变量获取配置
const title = import.meta.env.VITE_title;
const userAvatar = import.meta.env.VITE_userAvatar;
const userName = import.meta.env.VITE_userName;
const aiAvatar = import.meta.env.VITE_aiAvatar;
const aiName = import.meta.env.VITE_aiName;
const initMessage = import.meta.env.VITE_initMessage;
const logo = import.meta.env.VITE_logo;

const { streamChat, isLoading, error } = useChat();

const messages = ref<Message[]>([]);
const inputMessage = ref('');
const currentAssistantMessage = ref('');
const messagesContainer = ref<HTMLElement | null>(null);
const isTyping = ref(false); // 是否正在打字

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick();
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
  }
};

// 监听消息列表变化，滚动到底部
watch(messages, () => {
  scrollToBottom();
}, { deep: true });

// 格式化消息文本，处理换行符和链接
const formatMessage = (text: string) => {
  if (!text) return '';
  
  // 将换行符转换为 <br>
  const withLineBreaks = text.replace(/\n/g, '<br>');
  
  // 将URL转换为链接
  const withLinks = withLineBreaks.replace(
    /(https?:\/\/[^\s]+)/g, 
    '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>'
  );
  
  // 如果是最后一条AI消息且正在打字中，添加闪烁光标
  if (isTyping.value && messages.value.length > 0 && 
      messages.value[messages.value.length - 1].content === text && 
      messages.value[messages.value.length - 1].role === 'assistant') {
    return `${withLinks}<span class="cursor"></span>`;
  }
  
  return withLinks;
};

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value) return;
  
  // 添加用户消息
  const userMessage: Message = {
    role: 'user',
    content: inputMessage.value.trim()
  };
  messages.value.push(userMessage);
  
  // 清空输入框
  inputMessage.value = '';
  
  // 清空当前AI回复
  currentAssistantMessage.value = '';
  
  // 创建包含历史消息的数组
  const messageHistory = [...messages.value];
  
  // 添加AI消息占位
  messages.value.push({
    role: 'assistant',
    content: ''
  });
  
  // 设置正在打字状态
  isTyping.value = true;
  
  // 流式接收AI回复
  await streamChat(
    messageHistory,
    (chunk) => {
      // 累积响应文本
      currentAssistantMessage.value += chunk;
      // 更新最后一条消息（AI回复）
      messages.value[messages.value.length - 1].content = currentAssistantMessage.value;
    },
    () => {
      // 消息接收完成
      currentAssistantMessage.value = '';
      // 结束打字状态
      isTyping.value = false;
    }
  );
  
  if (error.value) {
    // 如果有错误，显示错误消息
    messages.value[messages.value.length - 1].content = `抱歉，发生了错误: ${error.value}`;
    isTyping.value = false;
  }
};

// 处理回车键
const handleEnterKey = (e: KeyboardEvent) => {
  // 按下Shift+Enter时插入换行符
  if (e.shiftKey) return;
  
  // 仅按下Enter时发送消息
  sendMessage();
};

// 组件挂载后滚动到底部
onMounted(() => {
  scrollToBottom();
});
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  max-width: 1000px;
  margin: 0 auto;
  padding: 1rem;
  box-sizing: border-box;
}

/* 头部容器样式 */
.header-container {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin-bottom: 1rem;
  gap: 12px;
  padding-left: 1rem;
}

/* Logo 样式 */
.logo {
  max-width: 160px;  /* 进一步缩小 */
  height: auto;
  object-fit: contain;
}

.chat-title {
  text-align: center;
  color: #333;
  margin: 0; /* 移除默认margin */
  font-size: 1.5rem; /* 稍微减小标题尺寸以匹配logo */
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 1rem;
  background-color: #f5f5f5;
  border-radius: 8px;
  margin-bottom: 1rem;
}

.message-wrapper {
  display: flex;
  margin-bottom: 1rem;
  animation: fadeIn 0.3s ease-in-out;
}

.user-message {
  flex-direction: row-reverse;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  margin: 0 0.5rem;
  flex-shrink: 0;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.message-content {
  max-width: 70%;
  display: flex;
  flex-direction: column;
}

.ai-message .message-content {
  align-items: flex-start;
}

.user-message .message-content {
  align-items: flex-end;
}

.message-sender {
  font-size: 0.8rem;
  color: #666;
  margin-bottom: 0.25rem;
}

.message-text {
  padding: 0.75rem 1rem;
  border-radius: 1rem;
  background-color: white;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  line-height: 1.5;
}

.ai-message .message-text {
  background-color: white;
  border-top-left-radius: 0;
}

.user-message .message-text {
  background-color: #1e88e5;
  color: white;
  border-top-right-radius: 0;
}

/* 打字效果的光标 */
.cursor {
  display: inline-block;
  width: 2px;
  height: 1.2em;
  background-color: #333;
  vertical-align: text-bottom;
  margin-left: 1px;
  animation: blink 0.8s step-end infinite;
  position: relative;
  opacity: 0.8;
  border-radius: 1px;
}

/* 光标闪烁动画 */
@keyframes blink {
  0%, 100% { opacity: 0.8; }
  50% { opacity: 0; }
}

/* 打字中的消息 */
.message-text.typing {
  /* 确保在内容增加时有平滑过渡 */
  transition: all 0.05s ease-out;
}

/* 添加响应式光标设计 */
@media (max-width: 768px) {
  .cursor {
    height: 1em;
    width: 1.5px;
  }
  
  .message-content {
    max-width: 85%; /* 在小屏幕上增加消息宽度 */
  }
  
  .logo {
    max-width: 120px; /* 在小屏幕上进一步缩小logo */
  }
  
  .chat-title {
    font-size: 1.2rem; /* 在小屏幕上减小标题尺寸 */
  }
}

/* 打字效果动画 */
@keyframes typing {
  from { width: 0 }
  to { width: 100% }
}

/* 在不同的设备和深色/浅色模式下调整光标颜色 */
@media (prefers-color-scheme: dark) {
  .cursor {
    background-color: #ddd;
  }
}

.chat-input-container {
  display: flex;
  gap: 0.5rem;
}

.chat-input {
  flex: 1;
  min-height: 60px;
  max-height: 150px;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 8px;
  resize: vertical;
  font-family: inherit;
  font-size: 1rem;
  outline: none;
}

.chat-input:focus {
  border-color: #1e88e5;
  box-shadow: 0 0 0 2px rgba(30, 136, 229, 0.2);
}

.send-button {
  align-self: flex-end;
  padding: 0.75rem 1.5rem;
  background-color: #1e88e5;
  color: white;
  border: none;
  border-radius: 8px;
  font-weight: bold;
  cursor: pointer;
  transition: background-color 0.2s;
}

.send-button:hover:not(:disabled) {
  background-color: #1976d2;
}

.send-button:disabled {
  background-color: #b0bec5;
  cursor: not-allowed;
}

.loading-indicator {
  display: flex;
  justify-content: center;
  gap: 0.5rem;
  margin: 1rem 0;
}

.dot {
  width: 8px;
  height: 8px;
  background-color: #1e88e5;
  border-radius: 50%;
  animation: bounce 1.4s infinite ease-in-out both;
}

.dot:nth-child(1) {
  animation-delay: -0.32s;
}

.dot:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes bounce {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
